package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Setmeal;
import com.itheima.service.Redis4SetMealCacheService;
import com.itheima.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * 套餐管理
 */
@RestController
@RequestMapping("/setmeal")
public class SetmealController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private SetmealService setmealService;
    @Reference
    private Redis4SetMealCacheService redis4SetMealCacheService;
    //查询所有的套餐信息
    @RequestMapping("/getSetmeal")
    public Result getSetmeal(){
        List<Setmeal> list = null;
        Gson gson = new Gson();
        try {
            String allSetMeal = jedisPool.getResource().get("setmeallist");
            if (allSetMeal != null) {
                list = gson.fromJson(allSetMeal, new TypeToken<List<Setmeal>>() {
                }.getType());
                System.out.println("======redis缓存取所有的套餐信息=========");

                return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS, list);
            }
            System.out.println("======没有走redis=======");
            list = setmealService.findAll();
            redis4SetMealCacheService.pushAllSetMeal2Cache(list);
            return new Result(true, MessageConstant.GET_SETMEAL_LIST_SUCCESS, list);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_SETMEAL_LIST_FAIL);
        }
    }

    //根据套餐id查询套餐详情
    @RequestMapping("/findFullById")
    public Result findFullById(Integer id){
        Setmeal setmeal = null;
        Gson gson = new Gson();
        try {
            String s = jedisPool.getResource().get("setmeal" + id);
            if (s != null) {
                setmeal = gson.fromJson(s, Setmeal.class);
                return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
            }
            setmeal = setmealService.findFullById(id);
            redis4SetMealCacheService.pushSetMeal2Cache(setmeal);
            return new Result(true, MessageConstant.QUERY_SETMEAL_SUCCESS, setmeal);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SETMEAL_FAIL);
        }
    }
}
